package com.freemalll.merchant.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.common.Constant;
import com.freemalll.merchant.constant.RedisKeyConstant;
import com.freemalll.merchant.domain.dto.SysConfigDto;
import com.freemalll.merchant.domain.entity.common.SysConfig;
import com.freemalll.merchant.mapper.common.SysConfigMapper;
import com.freemalll.merchant.service.SysConfigService;
import com.freemalll.merchant.utils.RedisUtil;
import com.freemalll.merchant.utils.common.QueryUtil;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * <p>
 * 系统配置表 服务实现类
 * </p>
 *
 * @author songshixiong
 * @since 2025-06-20
 */
@Service
@Transactional(rollbackFor = Exception.class )
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public Page<SysConfig> pageSearch(SysConfigDto dto) {
        QueryWrapper<SysConfig> wrapper = QueryUtil.getQueryWrapper(dto);
        wrapper.lambda().orderByDesc(SysConfig::getAddTime);
        return this.page(dto.page(), wrapper);
    }

    @Override
    public boolean refreshConfigCache() {
        //批量删除，根据key模糊
        redisUtil.removeAll(RedisKeyConstant.COM_FREE_MALL_COLLECT_CONFIG);
        //获取启用的配置数据重新放入redis
        List<SysConfig> list = baseMapper.selectList(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getCoEnable, 1));
        //暂时设置缓存5天
        list.forEach(config -> {
            String newKey = RedisKeyConstant.COM_FREE_MALL_COLLECT_CONFIG + config.getCoKey();
            redisUtil.set(newKey, JSON.toJSONString(config), RedisKeyConstant.CONFIG_KEY_TIME);
        });
        return true;
    }

    @Override
    public boolean editConfig(SysConfigDto dto) {
        if (dto == null || StringUtil.isBlank(dto.getCoKey())) {
            throw BusinessException.businessDataNotExist("参数不能为空");
        }
        if (StringUtil.isNotBlank(dto.getCoId())) {
            //修改
            SysConfig sysCfg = baseMapper.selectOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getCoId, dto.getCoId()));
            if (sysCfg == null) {
                throw BusinessException.businessDataNotExist("配置信息不存在，修改失败");
            }
            BeanUtils.copyProperties(dto, sysCfg);
            baseMapper.updateById(sysCfg);
            redisUtil.remove(RedisKeyConstant.COM_FREE_MALL_COLLECT_CONFIG + sysCfg.getCoKey());
            //把数据放入redis
            redisUtil.set(RedisKeyConstant.COM_FREE_MALL_COLLECT_CONFIG + sysCfg.getCoKey(), JSON.toJSONString(sysCfg), RedisKeyConstant.CONFIG_KEY_TIME);
        } else {
            //新增
            SysConfig sysCfg = baseMapper.selectOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getCoKey, dto.getCoKey()));
            if (Objects.nonNull(sysCfg)) {
                throw BusinessException.businessDataNotExist("key值已存在，请重新输入");
            }
            SysConfig save = Convert.convert(SysConfig.class, dto);
            baseMapper.insert(save);
            //把数据放入redis
            redisUtil.set(Constant.COM_FREE_MALL_COLLECT_CONFIG + save.getCoKey(), JSON.toJSONString(save), RedisKeyConstant.CONFIG_KEY_TIME);
        }
        return true;
    }

    @Override
    public SysConfig getConfigEntityByKey(String key) {
        //先从缓存中取
        String rkey = RedisKeyConstant.COM_FREE_MALL_COLLECT_CONFIG + key;
        Object o = redisUtil.get(rkey);
        SysConfig sysCfg;
        if (null == o) {
            //从数据库中取
            sysCfg = baseMapper.selectOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getCoKey, key).eq(SysConfig::getCoEnable, 1));
            if (!Optional.ofNullable(sysCfg).isPresent()) {
                throw BusinessException.businessDataNotExist("配置不存在，请检查");
            }
            redisUtil.set(rkey, JSON.toJSONString(sysCfg), RedisKeyConstant.CONFIG_KEY_TIME);
        } else {
            sysCfg = JSON.parseObject(o.toString(), SysConfig.class);
            if (Boolean.FALSE.equals(sysCfg.getCoEnable())) {
                throw BusinessException.businessDataNotExist("配置未启用，请检查");
            }
        }
        return sysCfg;
    }
}
